package org.iplugin.version.handler;

import org.iplugin.version.IVersionAbstractUpdateMojo;
import org.iplugin.version.model.IModifiedPomVersion;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;

/**
 * 　　* @Description: maven dependency version update
 * 　　* @author shangyouzhi1
 * 　　* @date 2022/11/27 15:01
 */
public class IVersionUpdateDependencyHandler extends IVersionUpdateAbstractHandler {

    public IVersionUpdateDependencyHandler() {
        this.setNextHandler(new IVersionUpdatePropertyHandler());
    }

    @Override
    public void updateVersion(IModifiedPomVersion modifiedPomVersion) {
        this.getLog().info("开始更新dependency version");
        Model model = modifiedPomVersion.getModel();
        List<Dependency> dependencies = this.getDependency(model);
        for (Dependency dependency : dependencies) {
            String dependencyVersion = dependency.getVersion();
            String newVersion = IVersionAbstractUpdateMojo.newVersionMap.get(dependency.getGroupId() + ":" + dependency.getArtifactId());
            if (StringUtils.isNotBlank(newVersion) && !StringUtils.equals(dependencyVersion, newVersion)) {
                this.getLog().info("更新jar包版本：" + dependency.getGroupId() + ":" + dependency.getArtifactId() + "更新前：" + dependencyVersion + ",更新后：" + newVersion);
                if (!StringUtils.startsWith(dependencyVersion, "${")) {
                    dependency.setVersion(newVersion);
                    modifiedPomVersion.modifiedVersion();
                }
            }
            if (getNextHandler() != null) {
                getNextHandler().updateVersion(modifiedPomVersion);
            }

        }

    }
}
